'use strict';

const path = require('path');
const CompressionWebpackPlugin = require('compression-webpack-plugin');

// 项目配置文件
// require('./build/index.js');

// path组合
const resolvePath = dir => path.resolve(__dirname, dir);

// 是否dev环境
const isDev = process.env.NODE_ENV === 'development';

module.exports = {
    outputDir: 'dist', // 打包输出目录
    publicPath: '/',
    assetsDir: 'static', // 放置静态资源的目录
    lintOnSave: isDev, // dev环境保存时触发eslint
    devServer: {
        host: '0.0.0.0',
        port: '8086',
        open: true,
        overlay: { // 浏览器关闭eslint警告和错误
            warnings: false,
            errors: true
        }
    },
    css: {
        extract: true, // 将css提取到一个单独的文件中而不是注入到js中
        loaderOptions: {
            scss: {
                prependData: `
                    @import "~@assets/styles/mixin.scss";
                    @import "~@assets/styles/var.scss";
                `
            }
        }
    },
    chainWebpack: config => {
        if (!isDev) {
            config.plugins.delete('prefetch');
            config.plugins.delete('preload');
            config.plugin('compress').use(CompressionWebpackPlugin, [
                {
                    test: /\.js$|\.html$|\.css$/, //需要压缩的文件正则
                    threshold: 10240, // 超过10kb就压缩
                    deleteOriginalAssets: false //压缩后保留原文件
                }
            ]);
        }
        // 别名
        config.resolve.alias
            .set('@', resolvePath('src'))
            .set('@components', resolvePath('src/components'))
            .set('@views', resolvePath('src/views'))
            .set('@assets', resolvePath('src/assets'))
            .set('@utils', resolvePath('src/utils'))
            .set('@services', resolvePath('src/services'))
            .set('@filters', resolvePath('src/filters'))
    },
    configureWebpack: config => {
        if (!isDev) {
            // 将每个依赖包打包成单独的js文件
            let optimization = {
                runtimeChunk: 'single',
                splitChunks: {
                    chunks: 'all',
                    maxInitialRequests: Infinity,
                    minSize: 20000, // 依赖包超过20000bit将被单独打包
                    cacheGroups: {
                        vendor: {
                            test: /[\\/]node_modules[\\/]/,
                            name(module) {
                                //node_modules/packageName
                                const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];
                                // 处理package里面的引用包
                                return `npm.${packageName.replace('@', '')}`;
                            }
                        }
                    }
                }
            };
            Object.assign(config, {
                optimization
            });
        }
    }
};
